import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../services/token_manager.dart';
import '../services/constants.dart';
import 'publish_product_screen.dart';
import 'goodsDetail.dart';
import '../servers/api_service.dart';
import '../services/market_events.dart';
import '../services/sold_cache.dart';

class MarketScreen extends StatefulWidget {
  @override
  State<MarketScreen> createState() => _MarketScreenState();
}

class _MarketScreenState extends State<MarketScreen> with TickerProviderStateMixin {
  List<dynamic> categoryList = [{'id': 0, 'name': '全部'}];
  List<dynamic> goodsList = [];
  TabController? tabController;
  String userEmail = '';
  String userName = '';
  String userAvatar = '';

  @override
  void initState() {
    super.initState();
    _initUser();
    // 监听发布/删除后的全局刷新事件
    MarketEvents.instance.notifier.addListener(() async {
      if (tabController != null && categoryList.isNotEmpty) {
        final currentId = categoryList[tabController!.index]['id'] as int;
        await _loadGoodsByCategory(currentId);
        if (mounted) setState(() {});
      } else {
        await _loadCategoryAndGoods();
      }
    });
  }

  Future<void> _initUser() async {
    final userInfo = await TokenManager.instance.getUserInfo();
    userEmail = userInfo?['email'] ?? '';
    userName = userInfo?['username'] ?? '';
    userAvatar = userInfo?['avatar'] ?? '';

    // 如果本地没有头像，尝试从后端拉取并缓存
    if (userEmail.isNotEmpty && (userAvatar.isEmpty)) {
      try {
        final res = await ApiService().getUserAvatar(userEmail);
        final remoteAvatar = (res != null) ? (res['avatar'] ?? res['data']?['avatar']) : null;
        if (remoteAvatar != null && remoteAvatar is String && remoteAvatar.isNotEmpty) {
          userAvatar = remoteAvatar;
          // 写回本地缓存，保持统一来源
          await TokenManager.instance.saveUserInfo(
            email: userEmail,
            username: userName,
            avatar: userAvatar,
          );
        }
      } catch (_) {}
    }
    await _loadCategoryAndGoods();
    setState(() {});
  }

  Map<String, String> _buildHeaders() {
    return {
      'Content-Type': 'application/json',
      if (userEmail.isNotEmpty) 'email': userEmail,
    };
  }

  Future<void> _loadCategoryAndGoods() async {
    final url = Uri.parse('${Constants.serverUrl}goods/getCategoryList');
    final res = await http.get(url, headers: _buildHeaders());
    if (res.statusCode == 200) {
      final data = jsonDecode(res.body);
      if (data['code'] == 0 && data['data'] is List) {
        setState(() {
          categoryList = [{'id': 0, 'name': '全部'}];
          categoryList.addAll(data['data']);
        });
      }
    }
    tabController = TabController(length: categoryList.length, vsync: this);
    tabController!.addListener(() async {
      if (!tabController!.indexIsChanging && tabController!.index < categoryList.length) {
        await _loadGoodsByCategory(categoryList[tabController!.index]['id']);
      }
    });
    await _loadGoodsByCategory(0);
    setState(() {});
  }

  Future<void> _loadGoodsByCategory(int categoryId) async {
    final url = Uri.parse('${Constants.serverUrl}goods/getGoodsList?categoryId=$categoryId');
    final res = await http.get(url, headers: _buildHeaders());
    if (res.statusCode == 200) {
      final data = jsonDecode(res.body);
      if (data['code'] == 0 && data['data'] is List) {
        final List<dynamic> raw = data['data'];
        final soldIds = await SoldCache.instance.getIds();
        final filtered = raw.where((e) {
          final isSold = e['isSold'] ?? e['is_sold'] ?? 0;
          final status = e['status'] ?? 0; // 有些后端可能直接返回状态
          final id = e['id'] is int ? e['id'] as int : int.tryParse((e['id'] ?? '').toString()) ?? 0;
          return isSold != 1 && status != 30 && !soldIds.contains(id); // 过滤已售/已完成/本地记录
        }).toList();
        setState(() {
          goodsList = filtered;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (tabController == null) {
      return Scaffold(appBar: AppBar(title: Text('市场')), body: Center(child: CircularProgressIndicator()));
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text('市场'),
        actions: [
          IconButton(
            icon: Icon(Icons.add_box_outlined),
            tooltip: '发布商品',
            onPressed: () async {
              final result = await Navigator.push(
                context,
                MaterialPageRoute(builder: (_) => PublishProductScreen()),
              );
              if (result == null) return;
              if (result is Map && result['success'] == true) {
                final int? catId = result['categoryId'] is int ? result['categoryId'] as int : null;
                if (catId != null && categoryList.isNotEmpty) {
                  // 找到对应分类索引
                  final idx = categoryList.indexWhere((e) => e['id'] == catId);
                  if (idx >= 0 && tabController != null && idx < tabController!.length) {
                    tabController!.animateTo(idx);
                    await _loadGoodsByCategory(categoryList[idx]['id']);
                    return;
                  }
                }
                // 回退逻辑：刷新当前分类
                if (tabController != null) {
                  await _loadGoodsByCategory(categoryList[tabController!.index]['id']);
                } else {
                  await _loadCategoryAndGoods();
                }
              } else if (result == true && tabController != null) {
                await _loadGoodsByCategory(categoryList[tabController!.index]['id']);
              }
            },
          ),
          Row(children: [
            if (userName.isNotEmpty) ...[
              Text(userName, style: TextStyle(fontSize: 14)),
              SizedBox(width: 8),
            ],
            if (userAvatar.isNotEmpty)
              CircleAvatar(backgroundImage: NetworkImage(userAvatar))
            else
              CircleAvatar(child: Icon(Icons.person)),
            if (userEmail.isNotEmpty)...[
              SizedBox(width: 8),
              Text(userEmail, style: TextStyle(fontSize: 12, color: Colors.grey)),
            ],
            SizedBox(width: 12),
          ]),
        ],
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(10),
            child: Container(
              height: 110,
              decoration: BoxDecoration(
                color: Colors.blue[50],
                borderRadius: BorderRadius.circular(12),
                image: DecorationImage(image: AssetImage('assets/images/banner.jpg'), fit: BoxFit.cover, opacity: 0.65),
              ),
            ),
          ),
          TabBar(
            controller: tabController,
            isScrollable: true,
            labelColor: Colors.blue[700],
            unselectedLabelColor: Colors.black54,
            tabs: categoryList.map((e) => Tab(text: e['name'])).toList(),
          ),
          Expanded(child: _buildProductGrid(goodsList)),
        ],
      ),
    );
  }

  Widget _buildProductGrid(List goodsList) {
    return GridView.builder(
      padding: const EdgeInsets.all(10),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
        childAspectRatio: 0.7,
      ),
      itemCount: goodsList.length,
      itemBuilder: (context, index) {
        final item = goodsList[index];
        final images = (item['images'] is String) ? item['images'].split(',') : [];
        return GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => GoodsDetailPage(goods: item),
              ),
            );
          },
          child: Card(
            clipBehavior: Clip.antiAlias,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: Container(
                    width: double.infinity,
                    color: Colors.grey[300],
                    child: images.isNotEmpty && images[0].isNotEmpty
                        ? Image.network(images[0], fit: BoxFit.cover)
                        : Icon(Icons.image_outlined, size: 50, color: Colors.grey[400]),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(item['name'] ?? '', style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500), maxLines: 1, overflow: TextOverflow.ellipsis),
                      const SizedBox(height: 4),
                      Text('¥${item['price']}', style: TextStyle(color: Colors.red[700], fontSize: 16, fontWeight: FontWeight.bold)),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}